package info.vanbeem.WikiMindDesktop;

import java.io.File;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

class FileTree {

	public FileTree(MainWindow mainWindow) {
		this.mainWindow = mainWindow;
		tree = mainWindow.getTree();
		
		tree.addListener (SWT.Selection, new Listener () {
			public void handleEvent (Event event) {
				itemClicked((TreeItem)event.item);
			}
		});
		mainWindow.setActiveFile(new File(mainWindow.getSettings().getSelectedItem()));
		fillTree();
	}

	private final MainWindow mainWindow;
	private final Tree tree;

	void fillTree() {
		// Fill the tree
		tree.removeAll();
		File root = new File(mainWindow.getSettings().getRootPath());
		if ( root.isDirectory() )
		{
			File[] files = root.listFiles();
			for (File child : files)
			{
				if ( child.isDirectory()) addEntry(child, null);
			}
			for (File child : files)
			{
				if ( child.isFile()) addEntry(child, null);
			}
		}
	}
	
	protected void addEntry(File root, TreeItem item) {
		TreeItem nextnode = null;
		if ( item == null )
		{
			nextnode = new TreeItem(tree, SWT.NONE);
		}
		else
		{
			nextnode = new TreeItem(item, SWT.NONE);
		}
		nextnode.setText(root.getName());
		nextnode.setData(root);
		
		
		if ( root.isDirectory() )
		{
			File[] files = root.listFiles();
			for (File child : files)
			{
				if (child.isDirectory()) addEntry(child, nextnode);
			}
			for (File child : files)
			{
				if (child.isFile()) addEntry(child, nextnode);
			}
		} else if ( root.getPath().equals(mainWindow.getActiveFile().getPath()) ) {
			tree.select(nextnode);
		}

	}
		
	private void itemClicked(TreeItem item)	{
		if (item != null)
		{
			mainWindow.setActiveFile((File)item.getData());
		}
		else {
			mainWindow.setActiveFile(null);
		}			
	}
}
